<!-- 导入多个jira -->
<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue"
import * as JiraApi from "@/api/jira"
import { CirclePlus } from "@element-plus/icons-vue"
import { type FormInstance, ElMessage } from "element-plus"
import { type JiraImportData } from "@/api/jira/types/jira"
import { type SelectData } from "@/api/common/types/common"
import { fetchSelectList } from "@/api/common"

// 定义触发父组件的事件
const emit = defineEmits<{
  (event: "set-loading", value: boolean): void // 设置父组件的 loading 状态
  (event: "operation-complete"): void // 操作完成的事件
}>()

// 项目下拉框
const projectSelectOptions = ref<SelectData[]>([])
const fetchProjectSelectOptions = async () => {
  const data = await fetchSelectList("project")
  projectSelectOptions.value = data.data
}

//#region 根据jira号导入
const importFormRef = ref<FormInstance>()
const dialogImportJiraVisible = ref(false)
// 待导入的jira信息
const jiraImportData = reactive<JiraImportData>({
  projectId: undefined,
  codes: [""]
})
// 当前选择的项目的jira前缀
const jiraPrefix = ref("")
const openImportJira = () => {
  dialogImportJiraVisible.value = true
  jiraImportData.projectId = undefined
  jiraImportData.codes = [""]
}

const colseImportJira = () => {
  dialogImportJiraVisible.value = false
  jiraImportData.projectId = undefined
  jiraImportData.codes = [""]
}

const handleImportJira = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    // 触发父组件的 loading 操作
    emit("set-loading", true) // 启动加载
    JiraApi.importJirasApi(jiraImportData)
      .then(({ data }) => {
        if (data) {
          ElMessage({
            message: data,
            type: "error",
            duration: 0,
            showClose: true,
            dangerouslyUseHTMLString: true
          })
        } else {
          ElMessage.success("导入成功")
        }
        dialogImportJiraVisible.value = false
      })
      .finally(() => {
        // 取消父组件的 loading
        emit("set-loading", false)
        // 操作完成后的通知
        emit("operation-complete")
      })
  })
}
// 新增一行 jira号
const handleImportJirAddRow = () => {
  jiraImportData.codes.push(jiraPrefix.value)
}

const handleImportJirRemoveRow = (index: number) => {
  jiraImportData.codes.splice(index, 1)
}
// 当项目变化时处理
const handleProjectChange = (projectId: number | undefined) => {
  const selectedProject = projectSelectOptions.value.find((project) => project.id === projectId)
  if (selectedProject) {
    jiraPrefix.value = String(selectedProject.pid) // 设置当前行的 jira前缀
    jiraImportData.codes = [jiraPrefix.value]
  } else {
    jiraPrefix.value = ""
  }
}

const jiraCodeRules = computed(() => {
  return [
    {
      required: true,
      message: "jira号必填",
      trigger: "blur"
    },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (jiraPrefix.value && value && !value.startsWith(jiraPrefix.value)) {
          callback(new Error(`jira号必须以 ${jiraPrefix.value} 开头`))
        } else {
          callback()
        }
      },
      trigger: "blur"
    }
  ]
})

onMounted(() => {
  fetchProjectSelectOptions()
})

// endregion
</script>

<template>
  <el-button size="small" type="success" :icon="CirclePlus" @click="openImportJira">导入jira号</el-button>

  <!--根据jira号导入 -->
  <el-dialog v-model="dialogImportJiraVisible" title="根据jira号从jira系统导入" @closed="colseImportJira" width="35%">
    <el-form ref="importFormRef" :model="jiraImportData" label-width="auto" label-position="left">
      <el-form-item
        prop="projectId"
        label="所属项目"
        :rules="[
          {
            required: true,
            message: '项目必填',
            trigger: ['blur', 'change']
          }
        ]"
      >
        <el-select
          v-model="jiraImportData.projectId"
          clearable
          filterable
          placeholder="请选择项目"
          @change="handleProjectChange(jiraImportData.projectId)"
        >
          <el-option v-for="item in projectSelectOptions" :key="item.id" :label="item.text" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item
        v-for="(code, index) in jiraImportData.codes"
        :key="index"
        :label="'jira号 ' + (index + 1)"
        :prop="'codes.' + index"
        :rules="jiraCodeRules"
      >
        <el-input v-model.trim="jiraImportData.codes[index]" placeholder="请输入jira号" />
        <el-button type="danger" text bg size="small" class="mt-2" @click.prevent="handleImportJirRemoveRow(index)"
          >删除</el-button
        >
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="success" @click="handleImportJirAddRow">新增一行</el-button>
      <el-button @click="dialogImportJiraVisible = false">取消</el-button>
      <el-button type="primary" @click="handleImportJira(importFormRef)">确认</el-button>
    </template>
  </el-dialog>
  <!--根据jira好导入 end-->
</template>

<style scoped lang="scss">
.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
}
.table-wrapper {
  padding: 10px;
}
</style>
